/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { PluginExtension } from './PluginExtension';

/**
 * Extension Manager
 *
 * Manages the registration and lifecycle of plugin extensions.
 * This singleton class
 * maintains a collection of all registered extensions and provides methods for
 * registering new extensions and retrieving the current set.
 */
export class ExtensionManager {
  /**
   * Singleton instance of the extension manager
   * @private
   */
  private static instance: ExtensionManager | null = null;

  /**
   * Array of registered extensions
   * @private
   */
  private extensions: PluginExtension[] = [];

  /**
   * Get the singleton instance of the extension manager
   *
   * Creates a new instance if one doesn't exist
   *
   * @returns {ExtensionManager} The singleton instance
   * @static
   */
  static getInstance(): ExtensionManager {
    if (!this.instance) {
      this.instance = new ExtensionManager();
    }
    return this.instance;
  }

  /**
   * Destroy the singleton instance
   *
   * Clears all registered extensions and resets the instance to null
   *
   * @static
   */
  static destroy(): void {
    this.instance = null;
    this.getInstance().clear();
  }

  /**
   * Register a new extension
   *
   * @param {PluginExtension} extension - The extension instance to register
   */
  registerExtension(extension: PluginExtension): void {
    this.extensions.push(extension);
  }

  /**
   * Get all registered extensions
   *
   * @returns {PluginExtension[]} Array of registered extensions
   */
  getExtensions(): PluginExtension[] {
    return this.extensions;
  }

  /**
   * Clear all registered extensions
   *
   * @private
   */
  private clear(): void {
    this.extensions = [];
  }
}

/**
 * Register a plugin extension
 *
 * Convenience function to register an extension with the extension manager
 *
 * @param {PluginExtension} extension - The plugin extension instance to register
 */
export function registerPluginExtension(extension: PluginExtension): void {
  ExtensionManager.getInstance().registerExtension(extension);
}
